﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp_Remote_Control.Utils
{
    internal class BitmapUtil
    {





        public static string BitmapToBase64(Bitmap bitmap, ImageFormat format)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream, format);
                byte[] imageBytes = memoryStream.ToArray();
                return Convert.ToBase64String(imageBytes);
            }
        }


        public static Bitmap Base64ToBitmap(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            using (MemoryStream memoryStream = new MemoryStream(imageBytes))
            {
                return new Bitmap(memoryStream);
            }
        }


        // 计算 Bitmap 的体积（字节数）
        public static long CalculateBitmapSize(Bitmap bitmap)
        {
            int width = bitmap.Width;
            int height = bitmap.Height;

            // 根据像素格式计算每个像素的字节数
            int bytesPerPixel = Image.GetPixelFormatSize(bitmap.PixelFormat) / 8;

            // 计算图像体积
            long sizeInBytes = width * height * bytesPerPixel;
            return sizeInBytes;
        }



        // 缩放 Bitmap
        public static Bitmap ScaleBitmap(Bitmap originalBitmap, int width, int height)
        {
            // 创建一个新的 Bitmap 来存储缩放后的图像
            Bitmap scaledBitmap = new Bitmap(width, height);

            // 创建 Graphics 对象来进行图像缩放
            using (Graphics g = Graphics.FromImage(scaledBitmap))
            {
                // 设置抗锯齿和高质量插值模式
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                // 绘制并缩放原始图像到目标图像
                g.DrawImage(originalBitmap, 0, 0, width, height);
            }

            return scaledBitmap;
        }


    }
}
